package com.qf.qfleadnewscommons.mvc;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UidHeaderInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取到请求头中的uid，存入到ThreadLocal对象
        String uid = request.getHeader("uid");
        System.out.println(uid);
        if (!StringUtils.isEmpty(uid)){
            ThreadLocalUtils.saveUid(Long.parseLong(uid));
        }
        return true;
    }

    // 处理器方法正常执行后，会触发的
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    // 处理器方法正常执行或者异常执行，都会触发的
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求结束，应该将ThreadLocal中的数据移除，防止内存泄露
        ThreadLocalUtils.removeUid();
    }
}
